<template>
  <Page :show-nav-bar="false" v-slot:default="{contentClass}" class="bg-gray-100">
    <div :class="contentClass" style="padding-top: 0;" >

      <LoadingBox v-if="pageLoading" class="w-40 h-40 absolute mt-8" style="z-index: 1; left: calc((100% - 10rem)/2)">
        <span>加载中...</span>
      </LoadingBox>

      <template v-else="!pageLoading">
        <van-swipe class="swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="(item, index) in activity.goods.goods_slider" :key="index">
            <van-image :src="item.url" fit="cover" style="height: 100%"/>
          </van-swipe-item>
        </van-swipe>

        <div class="specialBox w-full text-white overflow-hidden flex justify-between px-2 py-1">
          <div class="flex flex-col">
            <span class="text-sm">解锁价</span>
            <div class="priceBox ">
              <span :data-decimal="getPriceDecimal(activity.goods.discount_price)" class="costPrice">{{parseInt(activity.goods.discount_price)}}</span>
              <del class="text-sm ml-2">￥{{activity.goods.price}}</del>
            </div>
          </div>
          <div class="flex flex-col justify-between py-1">
            <div class="text-sm text-right">距离结束还剩</div>
            <van-count-down :time="downtime" millisecond>
              <template #default="timeData">
                <span class="block">{{ spaceNumber(timeData.hours) }}</span>
                <span class="colon">:</span>
                <span class="block">{{ spaceNumber(timeData.minutes) }}</span>
                <span class="colon">:</span>
                <span class="block">{{ spaceNumber(timeData.seconds) }}</span>
                <span class="colon">:</span>
                <span class="block">{{ spaceNumber(parseInt(timeData.milliseconds/10)) }}</span>
              </template>
            </van-count-down>
          </div>
        </div>

        <div class="bg-white box-border p-3">
          <div class="font-bold">{{activity.goods.name}}</div>
          <div class="text-sm mt-1">{{activity.goods.description}}</div>
        </div>

        <div class="p-3" v-html="activity.goods.content">

        </div>


        <div style="height: 3.125rem" class="bottom-safe"></div>

        <div class="fixed bg-white w-full bottom-0 shadow flex justify-between items-center px-2" style="height: 3.125rem">
          <template v-if="touchUser && touchUser.order && touchUser.order.is_pay">
            <div class="w-16 flex justify-center">
              <div class="flex flex-col justify-center">
                <van-icon name="service-o" color="#fa541c" size="1.5rem"/>
                <div class="text-xs w-full" style="color:#fa541c;" @click="onService">客服</div>
              </div>
            </div>
            <div class="flex-1">
              <van-button :disabled="touchUser.order.is_refund_applied" round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16);" class="w-full" @click="onMyRight">
                <div class="text-white">
                  查看解锁权益
                </div>
              </van-button>
            </div>
          </template>
          <template v-else>
            <span class="text-sm text-gray-500">原价：<del class="text-xs">￥{{activity.goods.price}}</del></span>
            <div style="width:60%;">
              <template v-if="downtime>0">
                <van-button round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16);" size="large" class="w-full" @click="onBuy">
                  <div class="text-white flex justify-center" style="font-size: .9rem;"><span>限时抢订特惠名额({{activity.goods.discount_price}}元)</span></div>
                  <div class="text-white text-xs flex justify-center mt-1">距结束：<van-count-down  class="text-white text-xs" :time="downtime" millisecond>
                    <template #default="timeData">
                      <span class="text-white text-xs">{{ spaceNumber(timeData.hours) }}:{{ spaceNumber(timeData.minutes) }}:{{ spaceNumber(timeData.seconds) }}:{{ spaceNumber(parseInt(timeData.milliseconds/10)) }}</span>
                    </template>
                  </van-count-down></div>
                </van-button>
              </template>
              <template v-else>
                <van-button round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16);" @click="showService=true" class="w-full">
                  <span class="text-white">活动已结束</span>
                </van-button>
              </template>
            </div>
          </template>
        </div>

        <float-menu v-model="collapseMenu" ref="floatMenu" @command="onCommand" style=""></float-menu>

        <van-popup v-model:show="showAuth" class="rounded-lg">
          <div class="p-4 flex flex-col items-center">
            <div class="text-lg text-center mb-4">
              微信授权
            </div>
            <van-image src="https://zdims-store.oss-cn-beijing.aliyuncs.com/goods_slider/2023-07-10/64ab728043d18.png" style="width: 4rem" class="mb-4"></van-image>
            <div class="mb-8">植得口腔医院</div>
            <div class="text-gray-500 text-xs mb-4" style="width: 16.4375rem;">
              为了确认您的权益信息，后续将会给您下发奖品奖励，需要授权您用户信息进行登录，请点击下方按钮进行授权。
            </div>
            <van-button round color="linear-gradient(to right, #fc491a, #ff660a)" class="w-full" @click="toLogin">微信授权</van-button>
          </div>
        </van-popup>

        <van-popup v-model:show="showPay"
           closeable
           position="bottom"
           :style="{ height: '80%' }"
           class="rounded-lg">
          <div class="relative">
              <div class="text-center border-b" style="line-height: 3.5rem;">支付详情</div>
              <div class="text-gray-400 px-4 py-2 border-box overflow-scroll" style="height: 23rem">
                <div class="text-xs">支付{{activity.goods.discount_price}}元可解锁权益</div>
                <div class="flex mt-3" v-for="el in rights.pay">
                  <van-image :src="el.cover.url" style="width: 6rem; height: 6rem;" round radius="5"></van-image>
                  <div class="pl-3 border-box relative" style="width: 14.6875rem;">
                    <div class="font-bold text-gray-500 text-sm truncate w-full">{{el.name}}</div>
                    <div class="text-xs truncate mt-1">{{el.description}}</div>
                    <div class="absolute bottom-2 text-xs text-orange-300">支付{{activity.goods.discount_price}}元邀请解锁</div>
                  </div>
                </div>

                <div class="text-xs mt-4">支付后，邀请好友解锁权益</div>
                <div class="flex mt-3" v-for="el in rights.assistance">
                  <van-image :src="el.cover.url" style="width: 6rem; height: 6rem;" round radius="5"></van-image>
                  <div class="pl-3 border-box relative" style="width: 14.6875rem;">
                    <div class="font-bold text-gray-500 text-sm truncate w-full">{{el.name}}</div>
                    <div class="text-xs truncate mt-1">{{el.description}}</div>
                    <div class="absolute bottom-2 text-xs text-orange-300">邀请{{el.unlock_config.count}}人可解锁</div>
                  </div>
                </div>
              </div>

              <div class="fixed bottom-0 w-full p-2 bg-white">
                <van-button round style="background: linear-gradient(90deg,#fa541c 0,#fa8c16);" size="large" class="w-full" @click="onOrder">
                  <div class="text-white" style="font-size: 1rem;">支付{{activity.goods.discount_price}}元解锁价购买</div>
                  <div class="text-white text-xs flex items-center mt-1">活动剩余结束：<van-count-down  class="text-white text-xs" :time="downtime" millisecond>
                    <template #default="timeData">
                      <span class="text-white text-xs">{{ spaceNumber(timeData.hours) }}:{{ spaceNumber(timeData.minutes) }}:{{ spaceNumber(timeData.seconds) }}:{{ spaceNumber(parseInt(timeData.milliseconds/10)) }}</span>
                    </template>
                  </van-count-down>
                  </div>
                </van-button>
              </div>
          </div>
        </van-popup>

        <van-popup v-model:show="showService" class="relative rounded-lg w-3/5" style="overflow-y: initial">
          <div class="w-full">
            <div class="p-3 border-b text-center">植得客服</div>
            <div class="p-3">
              <div class="text-red-600 flex justify-between text-sm items-center">
                <div>
                  <van-icon name="phone" size="1rem"/>
                  <span class="ml-2">{{activity.activity.extra.service_contact}}</span>
                </div>
                <van-button size="small" color="#ff0000" :url="'tel://'+activity.activity.extra.service_contact">一键拨打</van-button>
              </div>
            </div>
            <div class="border-t"></div>
            <div class="p-4">
              <van-image :src="activity.activity.extra.service_qrcode.url"></van-image>
            </div>
          </div>
          <div class="-mb-8 text-white text-center text-xl" @click="showService = false">
            <van-icon name="close"/>
          </div>
        </van-popup>

        <van-popup v-model:show="showActivity" class="relative rounded-lg w-4/5" style="overflow-y: initial">
          <div class="w-full">
            <div class="p-3 border-b text-center">
              我在植得做矫正
            </div>
            <div class="p-3 text-sm">邀请好友花多少返多少恭喜获得12元享特权资格</div>
            <div class="p-3">
              <van-form @submit="onSubmitApplyInfo">
                <van-cell-group inset>
                  <van-field v-model="applyInfo.name" label="姓名" placeholder="请输入姓名" :rules="[{ required: true, message: '请填写姓名' }]" />
                  <van-field v-model="applyInfo.mobile" label="电话" placeholder="请输入电话" :rules="[{ required: true, message: '请填写电话' }]"/>
                  <van-field
                      v-model="applyInfo.date"
                      is-link
                      readonly
                      name="datePicker"
                      label="时间选择"
                      placeholder="点击选择时间"
                      @click="showPicker = true"
                  />
                </van-cell-group>
                <div class="mt-6 mb-3">
                  <van-button round block type="primary" native-type="submit" :loading="store.state.loading.statuses['save_appointment_info']">
                    提交
                  </van-button>
                </div>
              </van-form>
            </div>
          </div>
          <div class="-mb-8 text-white text-center text-xl" @click="showActivity = false">
            <van-icon name="close"/>
          </div>
        </van-popup>

        <van-calendar v-model:show="showPicker" @confirm="onPickerConfirm" />

      </template>
    </div>
  </Page>
</template>

<script setup>
import bus from '../utils/bus'
import Page from "../components/Page.vue";
import {computed, nextTick, onActivated, onMounted, ref} from "vue";
import apis from '../apis'
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";
import app from "../configs/app";
import dayjs from 'dayjs';
import LoadingBox from "../components/LoadingBox.vue";
import FloatMenu from "../components/FloatMenu.vue";

const store = useStore()
const router = useRouter()
const route = useRoute()

const user = computed(() => store.state.user)
const userInfo = ref(null)
const touchUser = ref(null)
const activity = ref(null)
const downtime = ref(0)

const showAuth = ref(false)
const showService = ref(false)
const showPay = ref(false)

const showActivity = ref(false)
const applyInfo = ref({
  name: '',
  mobile: '',
  date: ''
})
const showPicker = ref(false)

const collapseMenu = ref(false)
const floatMenu = ref(null)

const getPriceDecimal = (price) => {
  let decimal = parseInt(parseInt(price * 100) % 100)
  return '.' + spaceNumber(decimal)
}

const spaceNumber = (num) => {
  return ((num+"").length==1 ? "0" + (num+"") : num)
}

const rights = computed(() => {

  if (!activity.value)
    return []

  let r = {
    "pay": [{
      name: activity.value.goods.name,
      cover: activity.value.goods.goods_cover,
      description: activity.value.goods.description,
      unlock_config: {"count": 0, "condition_type": "buy_once"},
      right: null // 当前本订单权益（即核销当前订单）
    }], // 即刻购权益
    "assistance": [] // 分享权益
  }

  activity.value.rights.forEach((el) => {
    if (el.unlock_config.condition_type == 'share_buy' || el.unlock_config.condition_type == 'share') {
      r.assistance.push(el)
    } else {
      r.pay.push(el)
    }
  })

  return r;
})

const onService = () => {
  showService.value = true
}

const onBuy = () => {
  if (!user.value.user) {
    showAuth.value = true
    return
  }

  // 已购买的订单
  if (touchUser.value) {
    if (touchUser.value.order && touchUser.value.order.is_pay) {
      // 查看我的权益
    } else {
      // 显示支付Popup
      showPay.value = true
    }
  }
}

const onOrder = async () => {
  await getUserInfo()

  /* 下单时保存之前填写的用户信息 */
  let activityInfo = localStorage.getItem('activity_info')
  if (activityInfo) {
    activityInfo = JSON.parse(activityInfo)
    let item = {
      'name': activityInfo.name,
      'mobile': activityInfo.mobile
    }
    if (userInfo.value.id) {
      await apis.user_info.update(item, {label: 'user_info_update', show_loading: true})
    } else {
      await apis.user_info.save(item, {label: 'user_info_update', show_loading: true})
    }
    await getUserInfo()

    await apis.activity.updateUser({"extra": {appointment_date: activityInfo.date}}, {label: 'user_update', show_loading: true, params: {id: activity.value.id}})

    localStorage.removeItem('activity_info')
  }


  if (!userInfo.value.name) { // 资料未完善
    store.state.statuses['return'] = true
    store.state.statuses['return_order'] = true
    await router.push({name: 'user_info'})
    return
  }

  toPay()
}

const toPay = () => {
  apis.order.store({
    "type": "goods_assistance",
    "activity_id": activity.value.id,
  }).then(({data: result}) => {
    location.href = app.payUrl + "?order_id=" + result.data.id + "&back_url=" +  encodeURIComponent(location.origin + location.pathname +  (app.history=='history'?'':'/#') + "/?activity_id=" + activity.value.id)
  })
}

const onMyRight = () => {
  router.push({name: 'right_got', query: {activity_id: activity.value.id}})
}

const toLogin = () => {
  localStorage.setItem('authCount', 0)
  localStorage.setItem('backPage', app.history == 'history' ? location.pathname : location.hash.substring(1)) // 当前请求路由，同时也包含的助力参数
  store.dispatch('user/wxAuth', {back: location.origin + location.pathname + (app.history=='history'?'':'/#') + '/login'}) // direct auth url
}

const getUserInfo = async () => {
  return await apis.user_info.show({label: 'user_info_get', show_loading: true}).then((resp) => {
    const result = resp.data
    userInfo.value = result.data || {
      name: '',
      mobile: '',
      gender: null
    }
    return userInfo.value
  })
}

const onCall = () => {
  window.location.href = 'tel://' + activity.value.activity.extra.service_contact
}

const pageLoading = ref(true)

const onCommand = (cmd) => {
  if (cmd == 'service') {
    onService()
  } else if(cmd == 'wallet') {
    if (!user.value.user) {
      toLogin()
    } else {
      router.push({name: "cash", query: {activity_id: activity.value.id}})
    }
  } else if(cmd == 'order') {
    if (!user.value.user) {
      toLogin()
    } else {
      router.push({name: "order", query: {activity_id: activity.value.id}})
    }
  }
}

const onPickerConfirm = (date) => {
  applyInfo.value.date = dayjs(date).format('YYYY-MM-DD')
  showPicker.value = false
}

const onSubmitApplyInfo = () => {
   localStorage.setItem('activity_info', JSON.stringify(applyInfo.value))

  let data = applyInfo.value
  apis.form.appointment(data, {
    label: 'save_appointment_info',
    show_loading: true
  }).then(() => {
    showActivity.value = false
  })
}

onMounted(async () => {
  await apis.activity.show({
    params: {
      id: route.query.activity_id,
    }
  }).then(({data: result}) => {
    activity.value = result.data
    downtime.value = dayjs(activity.value.activity.end_time).diff(new Date())
  })

  // 当完善信息返回后，立即支付
  if (store.state.statuses['return_order']) {
    await getUserInfo()

    if (userInfo.value.name) { // 资料已完善
      store.state.statuses['return_order'] = false
      toPay()
      return
    } else {
      store.state.statuses['return_order'] = false
    }
  }

  // 活动弹窗
  if (route.query.sid) { // 分享而来
    if (!user.value.user) { // 未授权时
      showActivity.value = true
    } else { // 针对相关活动已登录的用户
      let activityInfo = localStorage.getItem('activity_info')
      if (!activityInfo) {
        await apis.activity.user({
          params: {
            id: route.query.activity_id,
          }
        }).then(({data: result}) => {
          touchUser.value = result.data
        })
        if (!touchUser.value) { // 活动用户未创建
          showActivity.value = true
        }
      }
    }
  }

  // 确定邀请关系
  if (user.value.user) { // 微信授权登录后
    await apis.activity.touch({
      params: {
        id: route.query.activity_id,
        sid: route.query.sid // 保存邀请人id
      }
    }).then(({data: result}) => {
      touchUser.value = result.data
    })
  }
  pageLoading.value = false

  window.addEventListener('scroll', () => {
    if (floatMenu.value) {
      floatMenu.value.collapse()
    }
  }, true)
})
</script>

<style scoped>
  .swipe .van-swipe-item {
    color: #fff;
    font-size: 20px;
    height: 23.4375rem;
    text-align: center;
    background-color: #39a9ed;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .specialBox {
    position: relative;
    background: #fa541c;
  }

  .priceBox span.costPrice {
    font-weight: 700;
    font-size: 1.8rem;
    margin-left: -0.03rem;
  }

  .priceBox span.costPrice:before {
    content: "\FFE5";
    font-size: .8rem;
  }
  .priceBox span.costPrice:after {
    content: attr(data-decimal);
    font-size: .8rem;
  }

  .colon {
    display: inline-block;
    margin: 0 4px;
    color: #fff;
  }

  .block {
    display: inline-block;
    width: 22px;
    color: #fa541c;
    font-size: 12px;
    text-align: center;
    background-color: #fff;
    border-radius: .3rem;
  }
</style>